package com.borqsprocessmanager.db;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.borqsprocessmanager.db.DBProvider.ActionTable;

public class ActionContentProvider extends ContentProvider {

    private static HashMap<String, String> mActionMap;
    private static final int ACTION = 1;
    private static final int ACTION_ID = 2;

    private static final UriMatcher mUriMatcher;

    private DBHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = DBHelper.getInstance(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理

        case ACTION_ID:
            qb.appendWhere(ActionTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
        case ACTION:
            qb.setTables(ActionTable.TABLE_NAME);
            qb.setProjectionMap(mActionMap);
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = ActionTable.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
        case ACTION:
            return DBProvider.CONTENT_TYPE;
        case ACTION_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        ContentValues contentValues = null;
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String tableName = "";
        long rowId = 0;
        // String nullColumn = "";

        if (null != values) {
            contentValues = values;
        } else {
            contentValues = new ContentValues();
        }

        switch (mUriMatcher.match(uri)) {
        case ACTION:
            tableName = ActionTable.TABLE_NAME;
            Cursor c = queryProcessPkg(db, tableName, contentValues);
            if (c.getCount() == 0) {
                rowId = db.insert(tableName, null, contentValues);
            }
            break;
        default:
            break;
        }
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        return uri;
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int numValues = 0;
        db.beginTransaction(); // 开始事务
        try {
            // 数据库操作
            numValues = values.length;
            for (int i = 0; i < numValues; i++) {
                insert(uri, values[i]);
            }
            db.setTransactionSuccessful(); // 别忘了这句 Commit
        } finally {
            db.endTransaction(); // 结束事务
        }
        return numValues;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String finalWhere;
        int count;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理，注意下面用到的表名不要弄错了
        case ACTION:
            count = db.delete(ActionTable.TABLE_NAME, selection, selectionArgs);
            break;
        case ACTION_ID:
            finalWhere = DatabaseUtils.concatenateWhere(ActionTable._ID + " = "
                    + ContentUris.parseId(uri), selection);
            count = db
                    .delete(ActionTable.TABLE_NAME, finalWhere, selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        String finalWhere;

        switch (mUriMatcher.match(uri)) {
        case ACTION_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            selection = DatabaseUtils.concatenateWhere(
                    DBProvider.ActionTable._ID + " = "
                            + ContentUris.parseId(uri), selection);
        case ACTION:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.ActionTable.TABLE_NAME, values,
                    selection, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(ActionTable.AUTHORITY, ActionTable.TABLE_NAME,
                ACTION);
        mUriMatcher.addURI(ActionTable.AUTHORITY,
                ActionTable.TABLE_NAME + "/#", ACTION_ID);

        mActionMap = new HashMap<String, String>();
        mActionMap.put(ActionTable._ID, ActionTable._ID);
        mActionMap.put(ActionTable.ACATION_TYPE, ActionTable.ACATION_TYPE);
        mActionMap.put(ActionTable.PROCESS_NAME, ActionTable.PROCESS_NAME);
        mActionMap.put(ActionTable.APPNAME, ActionTable.APPNAME);
        mActionMap.put(ActionTable.PKG_NAME, ActionTable.PKG_NAME);
    }

    private Cursor queryProcessPkg(SQLiteDatabase db, String tableName,
            ContentValues contentValues) {
        String[] columns = new String[] { DBProvider.ActionTable._ID };
        String selecation = DBProvider.ActionTable.PROCESS_NAME + "=?";
        String[] selectionArgs = new String[] { contentValues
                .getAsString(DBProvider.ActionTable.PROCESS_NAME) };
        Cursor c = db.query(tableName, columns, selecation, selectionArgs,
                null, null, null, null);
        return c;
    }

}
